package com.trs.publish.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.trs.publish.aspect.Description;
import com.trs.publish.aspect.OperationDesc;
import com.trs.publish.domain.Power;
import com.trs.publish.domain.Role;
import com.trs.publish.domain.RolePower;
import com.trs.publish.domain.SearchParam;
import com.trs.publish.service.PowerService;
import com.trs.publish.service.RolePowerService;
import com.trs.publish.service.RoleService;


/**
 * 角色管理
 * @author jia.haihong
 *
 */

@Controller
public class RoleController{ 
	
	private static final Logger logger = LoggerFactory.getLogger(RoleController.class);
	
	@Autowired 
	private RoleService roleService;
	
	@Autowired 
	private PowerService powerService;
	
	@Autowired 
	private RolePowerService rolePowerService;
	
	
	@RequestMapping(value = "/toRole")
    public ModelAndView toUser(ModelAndView mav) {
        mav.setViewName("role/list");
        return mav;
    }  
	
	@PatchMapping(value = "/role")
    @ResponseBody
    public Object search(@RequestBody SearchParam searchParam) {
		String rolename = searchParam.getRolename();
		String memo = searchParam.getMemo();
		String startTime = searchParam.getStartTime();
		String endTime = searchParam.getEndTime();
		
		//根据查询条件获取列表
		Role role = new Role();
		role.setRolename(rolename);
		role.setMemo(memo);
		role.setStartTime(startTime);
		role.setEndTime(endTime);
		
		//mybatis分页
		PageHelper.startPage(searchParam);
		List<Role> list = roleService.getList(role);
		PageInfo<Role> pageInfo = new PageInfo<Role>(list);
        return pageInfo;
    }
	
	/**
	 * 删除
	 * 
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/role/{id}")
	@ResponseBody
	@OperationDesc(description = Description.delete_role)
	public Object delete(@PathVariable("id") long id) {
		Map<String, Object> map = new HashMap<String, Object>();
		logger.debug("删除角色id=" + id);
		//删除关联表信息
		rolePowerService.deleteByRoleId(id);
		//删除角色信息
		roleService.deleteRole(id);
		map.put("message", "删除成功！");
		return map;
	}
	
	/**
	 * 获取指定对象
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/role/{id}")
	public ModelAndView get(ModelAndView mav,@PathVariable("id") long id) {
		logger.debug("查询单个角色id=" + id);
		
		Role role = new Role();
		//权限列表
		List<Power> myPowers = new ArrayList<Power>();
		//获取信息
		if(id==0){
			role.setId(id);
		}else{
			role = roleService.findById(id);
			myPowers = powerService.getPowers(id);
		}
		List<String> myCheckPowers = new ArrayList<String>();
		if(myPowers!=null&&myPowers.size()>0) {
			for(Power power:myPowers) {
				myCheckPowers.add(power.getPowername());
			}
		}
		//权限列表
		List<Power> powers = powerService.getAllPowers();
		mav.addObject("powers", powers);
		mav.addObject("role", role);
		mav.addObject("myCheckPowers", myCheckPowers);
		mav.setViewName("role/detail");
		return mav;
	}
	
	/**
	 * 更新/新增
	 * 
	 * @param Role
	 * @return
	 */
	@PostMapping(value = "/role")
	@ResponseBody
	@OperationDesc(description = Description.addOrUpdate_role)
	public ModelAndView addOrUpdate(ModelAndView model,@Valid Role role, BindingResult result) {
		
		long id = role.getId();
		List<Power> myPowers = new ArrayList<Power>();
		 if(!result.hasErrors()){  
			if(id == 0){//新增方法
				//重置id
				role.setId(null);
				//保存角色信息
				roleService.save(role);
				id = role.getId();
			}else{//修改方法
				roleService.update(role);
				//删除关联表信息
				rolePowerService.deleteByRoleId(id);
				
			}
			
			//处理关系表信息
			List<RolePower> rp_List = new ArrayList<RolePower>();
			List<Long> powers = role.getPower();
			if(powers!=null&&powers.size()>0) {
				for(Long powerid:powers){
					if(powerid!=null){
						RolePower rp = new RolePower();
						rp.setPowerid(powerid);
						rp.setRoleid(id);
						rp_List.add(rp);
					}
				}
			}
			//保存角色权限关联表信息
			rolePowerService.batchSave(rp_List);
			myPowers  = powerService.getPowers(id);
			model.addObject("MSG", "提交成功！");
		}
		//权限列表
		 List<Power> powers = powerService.getAllPowers();
		 model.addObject("powers", powers);
		 List<String> myCheckPowers = new ArrayList<String>();
			if(myPowers!=null&&myPowers.size()>0) {
				for(Power power:myPowers) {
					myCheckPowers.add(power.getPowername());
				}
			}
		 model.addObject("myCheckPowers", myCheckPowers);
		 model.setViewName("role/detail");
		return model;
	}
}

